// scripts.ts
import $ from 'jquery';
import '../style/customer.scss';
import {
  isAndroid,
  ModalType,
  getQueryParamByName,
  fileUrlHandled,
  uploadErrorInfo,
  getBrowserType,
  BROWSER,
  isIOS,
  getCacheUUID,
  DomUtil,
  onloadImage,
  getEnTitleName,
} from '@/common/js/common';
import '@/common/phpFile/css/ba.css';
import '../style/download-h5.scss';
import '../style/animate.css';
import { nameConfig } from '@theme/vm';
import { Base64 } from 'js-base64';
import request from '../js/request';
import * as qs from 'qs';
import ProgressBar from 'progressbar.js';
import ClipboardJS from 'clipboard';
import queryString from 'query-string';
import ua2obj from 'ua2obj';

const SITE_NAME = process.env.SITE_NAME || '';
const imgPath = SITE_NAME + '_appdown';
const webClipPreUrl = '/api/findmed/v2/member/webclip/download';

export default function (appKey: string, type: 'sport' | 'site') {
  const i_code: any = getQueryParamByName('i_code');
  const r_code = getQueryParamByName('r_code');
  let app_android_download = '';
  let app_ios_download = '';
  let customer_service = '';
  const ios_download = nameConfig.ios_download; // ios线上包地址
  const android_download = nameConfig.android_download; // 安卓线上包地址

  let h5_domain = nameConfig.h5_domain;
  let locationIp = '';
  let ipAddress = '';

  // ----------------  webclicp ----------------------
  // 更新模态框内容  type1: IOS非safari浏览器  type2: IOS 未安装描述文件 type3 安卓下载
  function updateModalContent(type: string) {
    const subfix = i_code ? '?i_code=' + i_code : '';
    const homeUrl = `https://www.yl56.bet${subfix}`;
    // 模态框内容配置
    const modalContents = {
      iosNoSafari: {
        imageUrl: `/resource_images/${imgPath}/common/icon_safari.${window.supportWebp ? 'webp' : 'png'
          }?__static_hash__`,
        title: '使用safari浏览器',
        description: '桌面客服需要使用safrai下载描述文件并进行安装。',
        buttonText: '复制域名',
      },
      ios: {
        imageUrl: `/resource_images/${imgPath}/common/icon_seting.${window.supportWebp ? 'webp' : 'png'
          }?__static_hash__`,
        title: '安装描述文件',
        description: '在设置>通用>VPN与设备管理 可见描述文件。',
        buttonText: '桌面客服下载',
      },
      android: {
        imageUrl: `/resource_images/${imgPath}/common/logo.png?__static_hash__`,
        title: '下载到桌面?[如已下载请忽略]',
        description: `如无法正常下载到桌面,请下载【最新版本的Google浏览器】，打开Google浏览器，输入本站网址 ${homeUrl}，点击右上角的【菜单】然后选择【下载到桌面】即可完成WEB版APP`,
        buttonText: '下载到桌面',
      },
    };
    const content = modalContents[type];
    if (content) {
      if (type === ModalType.android) {
        $('#modal').css('display', 'none');
        $('#modalAndroid').css('display', 'flex');
        $('#modalAndroid .modal-image-android').attr('src', content.imageUrl);
        $('#modalAndroid .modal-title-android').text(content.title);
        $('#modalAndroid .modal-description-android').text(content.description);
      } else {
        $('#modal img').attr('src', content.imageUrl);
        $('#modal').css('display', 'flex');
        $('#modalAndroid').css('display', 'none');
        $('#modal .modal-title').text(content.title);
        $('#modal .modal-description').text(content.description);
        $('#modal .modal-button').text(content.buttonText);
      }
    }
  }

  function showModal(type: string) {
    $('#modal-overlay').css('visibility', 'visible');
    if (type === ModalType.android) {
      $('#modalAndroid').css('visibility', 'visible');
    } else {
      $('#modal').css('visibility', 'visible');
    }
    // 显示模态框
    $('#modal-overlay').fadeIn();

    // 关闭模态框
    $('#modal-overlay').click(() => {
      $('#modal-overlay').fadeOut();
    });

    // 关闭模态框 对应弹框 下载/复制按钮事件
    $('#modalButton').click(() => {
      modalBtnClick(type);
      $('#modal-overlay').fadeOut();
    });
    $('#modalButtonAndroidL').click(() => {
      $('#modal-overlay').fadeOut();
    });
    $('#modalButtonAndroidR').click(() => {
      modalBtnClick(type);
      $('#modal-overlay').fadeOut();
    });

    // 阻止modal内部点击事件冒泡
    $('#modal').click((event: Event) => {
      event.stopPropagation();
    });
    // 阻止modal内部点击事件冒泡
    $('#modalAndroid').click((event: Event) => {
      event.stopPropagation();
    });
  }

  function doPromptEvent() {
    if (window.savedPrompt) {
      const promptEvent = window.savedPrompt as any; // 类型断言，因为我们知道 savedPrompt 是什么
      promptEvent.prompt();
      // 等待用户做出响应
      promptEvent.userChoice.then((choiceResult: any) => {
        if (choiceResult.outcome === 'accepted') {
          console.log('用户接受了安装应用');
        } else {
          console.log('用户拒绝了安装应用');
        }
        window.savedPrompt = null;
      });
    }
  }
  function modalBtnClick(type: string) {
    const subfix = i_code ? '?i_code=' + i_code : '';
    const webclipUrl = `${webClipPreUrl}${subfix}`;
    console.log('不再是standalone模式', window, type);
    if (type === ModalType.iosNoSafari) {
      initCopyWebClip();
    } else {
      if (type === ModalType.android) {
        doPromptEvent();
      } else {
        // 下载 webclip
        fileUrlHandled(webclipUrl);
      }
    }
  }

  function initCopyWebClip() {
    const subfix = i_code ? '?i_code=' + i_code : '';
    const webclipUrl = `${webClipPreUrl}${subfix}`;

    navigator.clipboard
      .writeText(webclipUrl)
      .then(() => {
        alert('复制成功');
      })
      .catch(() => {
        alert('复制失败');
      });
  }
  // ----------------  webclicp ----------------------
  // 初始化 webClip 相关
  function initWebClip() {
    try {
      const fdqInstallBtn = document.querySelector<HTMLElement>('#fdqInstall');
      const isSafari = getBrowserType() === BROWSER.SAFARI;
      const modalType = isSafari
        ? ModalType.ios
        : isIOS()
          ? ModalType.iosNoSafari
          : ModalType.android;
      updateModalContent(modalType);
      if (fdqInstallBtn) {
        fdqInstallBtn.addEventListener('click', () => {
          setTimeout(() => {
            // 如果是 IOS safari 点击先下载再弹框
            if (modalType === ModalType.ios) {
              modalBtnClick(modalType);
            }
            showModal(modalType);
          }, 500);
        });
        fdqInstallBtn.style.opacity = '1';
        fdqInstallBtn.innerText = '立即下载';
        fdqInstallBtn.removeAttribute('disabled');
      }
    } catch (error) {
      uploadErrorInfo('game.installBtn.click', error, false);
    }
  }
  $(document).ready(function () {
    const customerTitle = document.querySelector<HTMLElement>('#customerTitle');
    try {
      const kefuBase64 = '5a6i5pyN';
      const customerTxt =
        getEnTitleName(nameConfig?.brand) +
        Base64.decode(`${nameConfig.brandName}`) +
        Base64.decode(kefuBase64) +
        Base64.decode('QXBw');
      if (customerTitle) {
        customerTitle.innerText = customerTxt;
      }

      document.title = customerTxt;
      // // 设置网页标题，这样做避免微信封杀
      // if (SITE_NAME === 'bw') {
      //   document.title = nameConfig.welComeText;
      // } else {
      //   if (i_code) {
      //     document.title =
      //       Base64.decode(
      //         `${nameConfig.welComeText}${nameConfig.brandName}QXBw`
      //       ) + i_code;
      //   } else if (r_code) {
      //     document.title =
      //       Base64.decode(
      //         `${nameConfig.welComeText}${nameConfig.brandName}QXBw`
      //       ) + r_code;
      //   } else {
      //     document.title = Base64.decode(
      //       `${nameConfig.welComeText}${nameConfig.brandName} QXBw`
      //     );
      //   }
      // }
    } catch (error) {
      uploadErrorInfo('game.setTitle', error, false);
    }
    // initWebClip();
    initCopy();
    initGetInfo();
    initTySCM();
    showDownloadTips();
    showICode();
    initReport();
    preloadImage();
    innitJiaocheng();
  });

  function innitJiaocheng() {
    const isAndroid = /Android/i.test(navigator.userAgent);
    const isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);

    if (isAndroid) {
      $('#serviceCardIos').hide();
      $('#serviceCardAndroid').show();
    } else if (isIOS) {
      $('#serviceCardAndroid').hide();
      $('#serviceCardIos').show();
    }

    // 切换教程tab
    function showTab(tabIndex) {
      $('.tab-button').removeClass('active');
      $('.tab-image').removeClass('active');
      $(`.tab-button[data-tab=${tabIndex}]`).addClass('active');
      $(`#tab${tabIndex}`).addClass('active');
    }

    // 读取url参数
    const urlParams = new URLSearchParams(window.location.search);
    const jiaocheng = urlParams.get('jiaocheng');

    // 如果带了参数显示教程tab
    if (jiaocheng === '1' || jiaocheng === '2') {
      $('#customer').hide();
      $('#tabContainer').show();
      showTab(parseInt(jiaocheng));
    } else {
      $('#customer').show();
      $('#tabContainer').hide();
    }

    $('#azjqBtn').click(function () {
      $('#customer').hide();
      $('#tabContainer').show();
      showTab(1);
    });

    $('#wfdkBtn').click(function () {
      $('#customer').hide();
      $('#tabContainer').show();
      showTab(2);
    });

    $('#returnBtn').click(function () {
      $('#tabContainer').hide();
      $('#customer').show();
    });

    $('.tab-button').click(function () {
      const tabIndex = $(this).data('tab');
      showTab(tabIndex);
    });
  }

  function clipboardInfos(): any {
    // 提取url参数
    const urlParams = qs.parse(window.location.search, {
      ignoreQueryPrefix: true,
    });
    const platform = isIOS() ? 'ios' : 'android';
    // 需要写入剪切板：appKey，设备参数，自定义参数
    const clipboardInfo = Object.assign({
      data: urlParams,
      url: location.href,
      hasData: Object.keys(urlParams).length > 0 ? 1 : 0,
      screen: window.screen.width * window.screen.height, // 屏幕宽高得出的积
      platform, // 平台类型
    });

    return clipboardInfo;
  }

  function initTySCM() {
    try {
      const downloadPanel = document.querySelector<HTMLElement>('#customer');
      const customerBtn = document.querySelector<HTMLElement>('#consultBtn');
      const customerJcBtn =
        document.querySelector<HTMLElement>('#customerJcBtn');
      if (downloadPanel) {
        DomUtil.show(downloadPanel);
        const gotoH5Btn = document.querySelector<HTMLElement>('#gotoH5');
        const appTitle = document.querySelector<HTMLElement>('#appTitle');

        if (appTitle) {
          let enName = '';
          // 这里处理title中英文混合Base64会出错问题
          if (nameConfig.brand === 'pgdz') {
            enName = 'PG';
          }
          appTitle.innerText =
            enName +
            Base64.decode(`${nameConfig.brandName}`) +
            Base64.decode('QXBw');
        }

        normalInit();

        customerBtn.addEventListener('click', function () {
          const subfix = i_code ? '?i_code=' + i_code : '';
          window.open(customer_service + subfix, '_blank');
        });
        customerJcBtn.addEventListener('click', function () {
          const subfix = i_code ? '?i_code=' + i_code : '';
          window.open(customer_service + subfix, '_blank');
        });
        gotoH5Btn.addEventListener('click', function () {
          const subfix = i_code ? '?i_code=' + i_code : '';
          window.location.href = h5_domain + subfix;
        });
      }
    } catch (error) {
      uploadErrorInfo('game.initTySCM', error, false);
    }
  }

  // 下载上报
  const toAppPostTycm = () => {
    const clipboardInfo = clipboardInfos();
    const data = JSON.stringify({
      ...clipboardInfo,
      startDownloadTime: parseInt(String(new Date().getTime() / 1000), 0),
    });
    const sendData = {
      data,
      device_uid: getCacheUUID(),
      device_uid_ip: `${getCacheUUID()}_${locationIp || ''}`,
    };
    request({
      url: '/api/findmed/v2/jbinstall/submitInfo',
      params: sendData,
      callback: (res: any) => {
        if (res.code === 6000) {
          //
        }
      },
      fail: (err: any) => {
        console.log(err);
      },
      method: 'post',
    });
  };

  /**
   * IOS进度条读完后处理
   *
   */
  function downloadComplete() {
    try {
      const installBtn = document.querySelector<HTMLElement>('#install');
      const installDiv = document.querySelector<HTMLElement>('#installDiv');
      const confirmCompletedElem =
        document.querySelector<HTMLElement>('.confirm_completed');
      const trustElem = document.querySelector<HTMLElement>('#trust');

      if (installBtn && installDiv) {
        installBtn.setAttribute('disabled', 'disabled');
        installDiv.style.display = 'none';
        const Button: any = isAndroid() ? trustElem : installBtn;
        DomUtil.addClass(Button, 'install_end');
        Button.innerHTML = `<img src="/resource_images/${imgPath}/common/icon_dui.${window.supportWebp ? 'webp' : 'png'
          }?__static_hash__"><span>${nameConfig.successText}</span>`;
      }
      if (isIOS()) {
        if (confirmCompletedElem) {
          confirmCompletedElem.innerText =
            '请确认APP下载完成后，再点击“一键信任”';
        }
        if (trustElem) {
          DomUtil.addClass(trustElem, 'trust_active');
          trustElem.addEventListener('click', function () {
            window.location.href = `/resource_images/${imgPath}/common/open.mobileprovision`;
          });
          trustElem.removeAttribute('disabled');
        }
      }
    } catch (error) {
      uploadErrorInfo('game.downloadComplete', error, false);
    }
  }

  /**
   * 展示下载的友好提示
   *
   */
  function showDownloadTips() {
    try {
      // 执行相关dom操作相关函数
      const elem = document.querySelector('.recommend-text');
      const elemGotoH5 = document.querySelector('.gotoH5');
      const eleTutoTxt = document.querySelector('.tutoTxt');

      if (elem) {
        // 设置浏览器文案提示
        if (isAndroid()) {
          elem.innerHTML = nameConfig.andrindRecommendText;
        } else {
          elem.innerHTML = nameConfig.iosRecommendText;
        }

        elemGotoH5.innerHTML = nameConfig.gotoH5Text;
        eleTutoTxt.innerHTML = nameConfig.tutoText;
      }
    } catch (error) {
      uploadErrorInfo('game.showDownloadTips', error, false);
    }
  }

  /**
   * 展示ICode
   *
   */
  function showICode() {
    try {
      if (i_code) {
        // 设置i_code字段
        const iCodePanel = document.querySelector<HTMLElement>('#show_i_code');

        if (iCodePanel) {
          iCodePanel.innerText = i_code === 'nobody' ? '' : i_code;
        }
      } else if (r_code) {
        // 设置r_code字段
        const iCodePanel = document.querySelector<HTMLElement>('#show_i_code');

        if (iCodePanel) {
          iCodePanel.innerText = r_code === 'nobody' ? '' : r_code;
        }
      }
    } catch (error) {
      uploadErrorInfo('game.showICode', error, false);
    }
  }

  function getProgressBarColo(brand: string) {
    const res = {
      color: '#ceb89f',
      trailColor: '#e6e1dc',
    };
    switch (brand) {
      case '10004':
        res.color = '#2043E4';
        res.trailColor = '#E6E1DC';
        break;
      case '10005':
        res.color = '#2043E4';
        res.trailColor = '#E6E1DC';
        break;
      default:
        break;
    }
    return res;
  }

  /**
   * 下载开始假的进度条
   *
   */
  function downloadProgress() {
    const installBtn = document.querySelector<HTMLElement>('#install');
    const trustElem = document.querySelector<HTMLElement>('#trust');
    const progress = document.querySelector<HTMLElement>('#progress');
    const progressContainer =
      document.querySelector<HTMLElement>('#progressContainer');
    let timer;
    let i = 30;
    const bar = new ProgressBar.Circle(progress, {
      strokeWidth: 5,
      easing: 'linear',
      duration: 1500,
      color: getProgressBarColo(nameConfig.brand).color,
      trailColor: getProgressBarColo(nameConfig.brand).trailColor,
      trailWidth: 5,
      svgStyle: null,
      step: (state, circle) => {
        const value = Math.round(circle.value() * 100);
        circle.setText(value + '%');
      },
    });
    // 下载时隐藏下载完成按钮 显示进度条及信任按钮
    if (installBtn && progressContainer) {
      installBtn.style.display = 'none';
      progressContainer.style.display = 'flex';
    }
    // 如果是安卓显示正在下载
    if (isAndroid()) {
      (trustElem as any).innerText = nameConfig.nowText + '...';
    }
    clearInterval(timer);
    timer = setInterval(() => {
      task();
    }, 1000);

    function task() {
      try {
        if (i <= 0) {
          bar.animate(1);
          setTimeout(() => {
            downloadComplete();
          }, 1500);
          clearInterval(timer);
          timer = null;
        } else {
          i--;

          if (Math.random() > 0.3 && installBtn) {
            const num = Math.floor(((30 - i) / 30) * 100);
            bar.animate(num / 100);
          }
        }
      } catch (error) {
        uploadErrorInfo('game.downloadProgress', error, false);
      }
    }
  }

  function normalInit() {
    const installBtn = document.querySelector<HTMLElement>('#install')!;
    const installDiv = document.querySelector<HTMLElement>('#installDiv');
    // 普通下载
    if (installBtn && installDiv) {
      installBtn.addEventListener('click', function () {
        try {
          toAppPostTycm();
          installBtn.setAttribute('disabled', 'disabled');
          installDiv.style.display = 'none';
          setTimeout(() => {
            if (isIOS()) {
              // window.location.href = app_ios_download;
              fileUrlHandled(app_ios_download);
            } else {
              window.location.href = app_android_download;
            }
          }, 200);

          installBtn.innerText = nameConfig.nowText + '...';
          setTimeout(function () {
            downloadProgress();
          }, 5000);
        } catch (error) {
          uploadErrorInfo('game.installBtn.click', error, false);
        }
      });
    }
  }

  function preloadImage() {
    // 全站图片列表
    const contentList = [
      {
        imgurl: `/resource_images/${imgPath}/download_v2/fullsite_content_page1.png?__static_hash__`,
      },
    ];

    onloadImage(contentList);
  }

  function initCopy() {
    // 需要写入剪切板：appKey，设备参数，自定义参数
    const clipboardInfo = clipboardInfos();
    const copyObj = new ClipboardJS('body', {
      text: () => {
        // 写入剪切板的格式：json字符串
        return Base64.encode(JSON.stringify(clipboardInfo));
      },
    });
  }

  /**
   * 第一次上报信息
   *
   */
  function initReport() {
    setTimeout(function () {
      // 刚进来页面时执行第一次日志上报
      const deviceInfo: any = ua2obj();
      if (ipAddress) {
        deviceInfo.ipAddress = ipAddress;
      }
      const query = queryString.parse(window.location.search || '');
      const params = {
        uuid: getCacheUUID(),
        client_type: 'h5',
        device: JSON.stringify(deviceInfo),
        value: JSON.stringify(query),
      };
      request({
        url: '/api/findmed/v2/jbinstall/addAppInfo',
        params,
        callback: (res: any) => {
          //
        },
        fail: (err: any) => {
          console.log(err);
        },
        method: 'post',
      });
    }, 1000);
  }

  // 请求前置信息
  function initGetInfo() {
    request({
      url: '/api/findmed/v2/member/preInfo',
      method: 'post',
      params: {},
      callback: (res: any) => {
        if (res.status) {
          const resData = res?.data;
          customer_service = res?.data?.customer_service || '';
          app_ios_download =
            resData?.site_domain?.app_ios_download || ios_download;
          app_android_download =
            resData?.site_domain?.app_android_download || android_download;
          // 这里循环判断返回的下载地址是否包含i_code或r_code，如果有就替换原来的下载地址
          for (let i = 1; i <= 3; i++) {
            const iosDownload =
              resData?.site_domain[`ios_download_url_${i}`] &&
              JSON.parse(resData?.site_domain[`ios_download_url_${i}`]);
            const androidDownload =
              resData?.site_domain[`android_download_url_${i}`] &&
              JSON.parse(resData?.site_domain[`android_download_url_${i}`]);
            if (
              iosDownload &&
              (iosDownload?.icode === i_code || iosDownload?.icode === r_code)
            ) {
              if (iosDownload?.url) {
                app_ios_download = iosDownload?.url;
              }
            }
            if (
              androidDownload &&
              (androidDownload?.icode === i_code ||
                androidDownload?.icode === r_code)
            ) {
              if (androidDownload?.url) {
                app_android_download = androidDownload?.url;
              }
            }
          }
          if (res?.data?.site_domain?.h5_domain) {
            h5_domain = res?.data?.site_domain?.h5_domain;
          }
        }
      },
      fail: (err: any) => {
        console.log(err);
      },
    });

    request({
      url: '/api/findmed/v2/jbinstall/ip/location',
      params: {},
      callback: (res: any) => {
        if (res.code === 0) {
          locationIp = res?.data?.ip;
          const country = res?.data?.country ?? '';
          const province = res?.data?.province ?? '';
          const city = res?.data?.city ?? '';
          const ipAddressArr = [locationIp, country, province, city];
          ipAddress = JSON.stringify(ipAddressArr);
        }
      },
      fail: (err: any) => {
        console.log(err);
      },
      method: 'post',
    });
  }
}
